var express = require('express');
var router = express.Router();
var mongoose = require('../models/db');
var commentModel = require('../models/commentModel');


/*保存景点*/
router.post('/add', function (req, res, next) {

    let dg_id = req.body.dg_id;
    let avatarUrl = req.body.avatarUrl;
    let nickName = req.body.nickName;
    let content = req.body.content;
    let time = req.body.time;
    let openid=req.body.openid;
    let userInfo=req.body.userInfo;
    const comDB = new commentModel({
        'openid':openid || '',
        'dg_id': dg_id || '',
        "avatarUrl": avatarUrl|| '',
        "content": content|| '',
        "nickName":nickName|| '',
        "time": time,
        "userInfo":userInfo
    });

    comDB.save(function (err, doc) {
        if (err) {
            res.json({
                success: false,
                msg: err.message
            });
        }
        else {

            res.json({
                success: true,
                msg: '提交成功！'
            })

        }
    })
});


//评论列表
router.post('/commentList', function (req, res, next) {
    let page = req.body.page;
    let limit = req.body.limit;
    let listType=req.body.listType;
    let dg_id=req.body.dg_id;
    var find=listType=='all'?{}:{'dg_id':dg_id}
    console.log(find)
    commentModel.count(find, function (err, count) {
        commentModel
            .find(find)
            .skip(page * limit)
            .limit(parseInt(limit))
            .sort({'_id': -1})
            .exec(function (err, doc) {
                if (err) {
                    res.json({
                        success: false,
                        msg: err.message,
                    });
                }
                else {

                    res.json({
                        success: true,
                        msg: '',
                        result: {
                            count: count,
                            list: doc
                        }
                    })
                }
            })
    });

});

//删除评论
router.post('/delComment', function (req, res, next) {
    let comment_id = req.body.comment_id;

    commentModel.remove({'_id': comment_id}, function (err, doc) {
        if (err) {
            res.json({
                success: false,
                msg: '删除失败！',
                result: ''
            });
        }
        else {

            res.json({
                success: true,
                msg: '删除成功！',
                result: ''
            })
        }
    })
});
module.exports = router;
